package com.xzlcPT.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.util.MD5;
import com.util.MakeKey;
import com.util.PageBean;
import com.xzlcPT.bean.*;
import com.xzlcPT.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller 层 LoginController
 *
 * @author 王天岳
 * @create 2017/3/30 17:43
 **/

@Controller
@RequestMapping("/XzLogin")
@SessionAttributes({"userLogin", "adminLogin"})
public class LoginController extends BaseController {

    @Autowired
    private LoginUserService loginService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private VipService vipService;

    //移动端。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

    //发送电话验证
    @ResponseBody
    @RequestMapping("/updataP.go")
    public Map updataP(String phone, @RequestHeader("accessToken") String token) {
        Map map = new HashMap();
        XzLogin xzLogin = loginService.selByToken(token);
//        XzLogin xzLogin = loginService.selByPhone(phone);
        try {
            String code;
            Date time = new Date();
            if (null != xzLogin.getLoginPhoneKey()) {//电话验证是否为空
                long sendTime = xzLogin.getLoginPhoneTime().getTime();
                if (sendTime + 600000 < time.getTime()) {//超过十分钟
                    code = MakeKey.getRandNum() + "";
                    xzLogin.setLoginPhoneKey(code);
                    xzLogin.setFiled1(phone);
                    xzLogin.setLoginPhoneTime(time);
                    loginService.updateByPrimaryKey(xzLogin);
                } else {
                    code = xzLogin.getLoginPhoneKey();
                }
            } else {
                code = MakeKey.getRandNum() + "";
                xzLogin.setLoginPhoneKey(code);
                xzLogin.setFiled1(phone);
                xzLogin.setLoginPhoneTime(time);
                loginService.updateByPrimaryKey(xzLogin);
            }
            Map mapContent = new HashMap();
            mapContent.put("name", xzLogin.getLoginCount());
            mapContent.put("code", code);
            mapContent.put("time", "10");
            ObjectMapper mapper = new ObjectMapper();
            String content = mapper.writeValueAsString(mapContent);//map转json
            String msg = send(content, phone, "414143");
            Map maps = mapper.readValue(msg, Map.class);//发送返回值转map
            System.out.println(maps);
            map.put("msg", "ok");
            map.put("sendMsg", maps);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "err");
        }
        return map;
    }

    //电话修改验证码验证
    @ResponseBody
    @RequestMapping("updataP_YZ.go")
    public Map updataP_YZ(String phone, String idcode, @RequestHeader("accessToken") String token) {
        Map map = new HashMap();
        XzLogin xzLogin = loginService.selByToken(token);
        if (phone != null && idcode != null && xzLogin.getLoginPhoneKey().equals(idcode) && xzLogin.getFiled1().equals(phone)) {
            xzLogin.setLoginPhone(phone);
            loginService.updateLoginEnd(xzLogin);
            map.put("msg", "ok");
        } else {
            map.put("msg", "电话或验证码错误");
        }
        return map;
    }


    //根据条件修改登录表信息
    @ResponseBody
    @RequestMapping("updatePasswordMob.go")
    public Map updatePasswordMob(String oldPassword, String newPassword, @RequestHeader("accessToken") String token) {
        Map map = new HashMap();
        XzLogin xzLogin = loginService.selByToken(token);
//        比较密码 若有改动则重新MD5加密
        if (xzLogin.getLoginPassword().equals(MD5.md5(oldPassword))) {
            xzLogin.setLoginPassword(MD5.md5(newPassword));
            if (xzLogin.getDeleteFalt() == 1) {
                xzLogin.setDeleteLoginDate(new Date());
            }
            if (oldPassword.equals(newPassword)) {
                map.put("msg", "新密码不能与原密码相同!");
            } else {
                int a = loginService.updateLoginEnd(xzLogin);
                if (a != 0) {
                    map.put("msg", "ok");
                    System.out.println("修改成功!");
                } else {
                    map.put("msg", "err");
                    System.out.println("修改失败!");
                }
            }
        } else {
            map.put("msg", "原密码错误!");
        }
        return map;
    }


    //账号密码登录
    @ResponseBody
    @RequestMapping("/LoginE.go")
    public Map loginGo(String username, String password) {
        Map map = new HashMap();
        Map mapR = loginService.sellogin(username, MD5.md5(password));
        if (mapR.get("msg").equals("miss")) {
            //没找到用户
            map.put("msg", "不存在此用户");
        } else if (mapR.get("msg").equals("err")) {
            //用户名或密码错误
            map.put("msg", "账号或密码错误");
        } else if (mapR.get("msg").equals("ok")) {
            XzLogin login = (XzLogin) mapR.get("login");
            map.put("msg", "ok");
            map.put("userType", login.getLoginType());
            String t = MD5.md5(new Date().getTime() + username);
            login.setLoginToken(t);
            int i = loginService.updateByPrimaryKey(login);
            if (i > 0) map.put("token", t);
        }
        return map;
    }

    //电话验证
    @ResponseBody
    @RequestMapping("/loginPK.go")
    public Map loginPK(XzLogin xzLogin) {
        Map map = new HashMap();
        XzLogin login = loginService.selByPK(xzLogin);
        if (login != null) {
            map.put("msg", "ok");
            map.put("userType", login.getLoginType());
            String t = MD5.md5(new Date().getTime() + login.getLoginPhone());
            login.setLoginToken(t);
            int i = loginService.updateByPrimaryKey(login);
            if (i > 0) map.put("token", t);
        } else {
            map.put("msg", "账号或验证码错误");
        }
        return map;
    }

    //发送电话验证
    @ResponseBody
    @RequestMapping("/loginP.go")
    public Map loginP(String phone) {
        Map map = new HashMap();
        map = loginYZ(phone);
        return map;
    }

    private Map loginYZ(String phone) {
        Map map = new HashMap();
        XzLogin xzLogin = loginService.selByPhone(phone);
        if (xzLogin != null) {
            try {
                String code;
                Date time = new Date();
                if (null != xzLogin.getLoginPhoneKey()) {//电话验证是否为空
                    long sendTime = xzLogin.getLoginPhoneTime().getTime();
                    if (sendTime + 600000 < time.getTime()) {//超过十分钟
                        code = MakeKey.getRandNum() + "";
                        xzLogin.setLoginPhoneKey(code);
                        xzLogin.setLoginPhoneTime(time);
                        loginService.updateByPrimaryKey(xzLogin);
                    } else {
                        code = xzLogin.getLoginPhoneKey();
                    }
                } else {
                    code = MakeKey.getRandNum() + "";
                    xzLogin.setLoginPhoneKey(code);
                    xzLogin.setLoginPhoneTime(time);
                    loginService.updateByPrimaryKey(xzLogin);
                }
                Map mapContent = new HashMap();
                mapContent.put("name", xzLogin.getLoginCount());
                mapContent.put("code", code);
                mapContent.put("time", "10");
                ObjectMapper mapper = new ObjectMapper();
                String content = mapper.writeValueAsString(mapContent);//map转json
                String msg = send(content, phone, "414143");
                Map maps = mapper.readValue(msg, Map.class);//发送返回值转map
                System.out.println(maps);
                map.put("msg", "ok");
                map.put("sendMsg", maps);
            } catch (Exception e) {
                e.printStackTrace();
                map.put("msg", "err");
            }
        } else {
            map.put("msg", "miss");
        }
        return map;
    }

    //短信发送
    private String send(String msgContent, String mobile, String template) throws Exception {
        String addr = "http://api.sms.cn/sms/";
        String userId = "aidan200";
        String pwd = "b7298cb8d99836a32c9c4ffe596bd142";
        String econd = "utf8";
        //组建请求
        String straddr = addr +
                "?ac=send&uid=" + userId +
                "&pwd=" + pwd +
                "&mobile=" + mobile +
                "&content=" + msgContent +
                "&econd=" + econd +
                "&template=" + template;
        StringBuffer sb = new StringBuffer(straddr);
        //System.out.println("URL:"+sb);
        //发送请求
        URL url = new URL(sb.toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        BufferedReader in = new BufferedReader(new InputStreamReader(
                url.openStream()));
        //返回结果
        String inputline = in.readLine();
        //System.out.println("Response:"+inputline);
        return inputline;
    }


    //token查询
    @ResponseBody
    @RequestMapping("/selToken.go")
    public Map selToken(String loginToken) {
        Map map = new HashMap();
        XzLogin login = loginService.selByToken(loginToken);
        if (login != null) {
            map.put("msg", "ok");
            map.put("userType", login.getLoginType());
        } else {
            map.put("msg", "miss");
        }
        return map;
    }

    //pc端。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

    //发送电话验证  ---登录
    @ResponseBody
    @RequestMapping("/loginPhoneSing.do")
    public Map loginPhone(String phone) {
        Map map = new HashMap();
        map = loginYZ(phone);
        return map;
    }

    //      手机登录方法
    @RequestMapping("LoginPhone.do")
    public ModelAndView getLoginPhone(String username, String password, String remember, HttpServletResponse response, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("foreEnd3/login");
        mv.addObject("username", username);
        String checkBox = remember;
        Map map = loginService.selloginPhone(username, password);
        if (map.get("msg").equals("miss")) {
            //没找到用户
            mv.addObject("msg", "不存在此用户");
        } else if (map.get("msg").equals("err")) {
            //用户名或密码错误
            mv.addObject("msg", "用户密码错误");
        } else if (map.get("msg").equals("ok")) {
            XzLogin login = (XzLogin) map.get("login");
            if (login.getLoginActive() == 0) {
                //账号没激活
                if (login.getLoginType() == 0) {
                    mv.setViewName("foreEnd3/registeru_1");
                    mv.addObject("xzLogin", login);
                    mv.addObject("state", 2);
                } else if (login.getLoginType() == 1) {
                    mv.setViewName("");
                }
                mv.addObject("msg", "账号未激活，请激活账号");
            } else {
                mv.setViewName("redirect:/");
                //session中存入当前用户
                mv.addObject("userLogin", login);
                //cookie记住用户
                if ("true".equals(checkBox)) {
                    String t = MD5.md5(new Date().getTime() + login.getLoginPhone());
                    login.setFiled3(t);
                    int i = loginService.updateByPrimaryKey(login);
                    Cookie cookies = new Cookie("cookieToken", t);
                    cookies.setMaxAge(3600 * 24 * 30);
                    //获取项目名
                    String b = request.getContextPath();
                    cookies.setPath(b + "/");
                    response.addCookie(cookies);
                }
            }
        }
        return mv;
    }

    //      登录方法
    @RequestMapping("/Login.do")
    public ModelAndView getLogin1(String username, String password, String remember, HttpServletResponse response, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("foreEnd3/login");
        mv.addObject("username", username);
        String checkBox = remember;
        Map map = loginService.sellogin(username, MD5.md5(password));
        System.out.println(map);
        if (map.get("msg").equals("miss")) {
            //没找到用户
            mv.addObject("msg", "不存在此用户");
        } else if (map.get("msg").equals("err")) {
            //用户名或密码错误
            mv.addObject("msg", "用户密码错误");
        } else if (map.get("msg").equals("ok")) {
            XzLogin login = (XzLogin) map.get("login");
            if (login.getLoginActive() == 0) {
                //账号没激活
                if (login.getLoginType() == 0) {
                    mv.setViewName("foreEnd3/registeru_1");
                    mv.addObject("xzLogin", login);
                    mv.addObject("state", 2);
                } else if (login.getLoginType() == 1) {
                    mv.setViewName("");
                }
                mv.addObject("msg", "账号未激活，请激活账号");
            } else {
                mv.setViewName("redirect:/");
                //session中存入当前用户
                mv.addObject("userLogin", login);
                //cookie记住用户
                if ("true".equals(checkBox)) {
                    String t = MD5.md5(new Date().getTime() + login.getLoginEmail());
                    login.setFiled3(t);
                    int i = loginService.updateByPrimaryKey(login);
                    Cookie cookies = new Cookie("cookieToken", t);
                    cookies.setMaxAge(3600 * 24 * 30);
                    //获取项目名
                    String b = request.getContextPath();
                    cookies.setPath(b + "/");
                    response.addCookie(cookies);
                }
            }
        }
        return mv;
    }

    //免登陆方法
    @ResponseBody
    @RequestMapping("/LoginCookie.do")
    public Map loginCookie(String cookieToken, Model model) {
        Map map = new HashMap();
        XzLogin xzLogin = loginService.selCookieToken(cookieToken);
        if (xzLogin != null) {
            XzLogin userLogin = loginService.selLoginByCT(xzLogin);
            if (userLogin != null) {
                model.addAttribute("userLogin", userLogin);
                map.put("msg", "ok");
            }
        }
        return map;
    }

    //    退出登录方法
    @RequestMapping("ExitUser.do")
    public ModelAndView exitUser(SessionStatus sessionStatus, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("redirect:/");
        sessionStatus.setComplete();//清空session
        //删除cookie
        Cookie[] cookies = request.getCookies();
        if (null == cookies) {
            System.out.println("没有cookie");
        } else {
            for (Cookie cookie : cookies) {
                //如果找到同名cookie，就将value设置为null，将存活时间设置为0，再替换掉原cookie，这样就相当于删除了。
                if (cookie.getName().equals("count") || cookie.getName().equals("pw")) {
                    cookie.setValue(null);
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        System.out.println("ExitUser");
        return mv;
    }


//    跳转到后台 查询所有登录表信息(分页查询)
    @RequestMapping("selAllLogin.emp")
    public ModelAndView selAllLoginEnd(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer rows, XzLogin xzLogin) {
        ModelAndView mv = new ModelAndView("backEnd/loginEnd");
        PageBean<XzLogin> pageBean = loginService.selAllLoginEnd(page, rows, xzLogin);
        List<XzLogin> loginList = pageBean.getList();
        mv.addObject("loginList", loginList);
        mv.addObject("page", pageBean.getPageNum());
        mv.addObject("pages", pageBean.getPages());
        mv.addObject("rows", pageBean.getPageSize());
        mv.addObject("total", pageBean.getTotal());
        mv.addObject("test", xzLogin);
        return mv;
    }

    @RequestMapping("goAddLogin.emp")
    public ModelAndView goAddLoginEnd() {
        ModelAndView mv = new ModelAndView("backEnd/updateLoginEnd");
        XzLogin xzLogin = new XzLogin();
        mv.addObject("xzLogin", xzLogin);
        return mv;
    }

    //    添加用户
    @RequestMapping("addLogin.emp")
    public ModelAndView addLoginEnd(@Validated({XzLogin.F1.class}) XzLogin xzLogin, BindingResult result) {
        ModelAndView mv = new ModelAndView("redirect:selAllLogin.emp");
        if (result.hasErrors()) {
            System.out.println("hasErrors:" + xzLogin);
            mv.setViewName("backEnd/updateLoginEnd");
        } else {
            xzLogin.setLoginPassword(MD5.md5(xzLogin.getLoginPassword()));
            int a = loginService.addLoginEnd(xzLogin);
            if (a != 0) {
                System.out.println("添加成功!");
                xzLogin = loginService.selLoginByCountEnd(xzLogin);
                if (xzLogin.getLoginType() == 1) {
                    XzMember xzMember = new XzMember();
                    //xzMember.setLoginId(xzLogin.getLoginId());
                    xzMember.setMemberPicture("timg1.jpg");
                    userInfoService.addUserInfo(xzMember);
                } else {
                    XzCompany xzCompany = new XzCompany();
                    xzCompany.setLoginId(xzLogin.getLoginId());
                    //xzCompany.setCompanyName(xzLogin.getCompanyName());
                    xzCompany.setCompanyPicture("timg1.jpg");
                    companyInfoService.insertCompanyInfo(xzCompany);
                }
                //添加 VIP
                Vip vip = vipService.selectVipByLoginID(xzLogin.getLoginId());
                if (vip == null) {
                    vip = new Vip();
                    vip.setLoginID(xzLogin.getLoginId());
                    vip.setVipRest(0.00);
                    vip.setVipScore(0L);
                    int va = vipService.insertVip(vip);
                    if (va != 0) {
                        System.out.println("添加VIP成功");
                    } else {
                        System.out.println("添加VIP失败");
                    }
                }
            } else {
                System.out.println("添加失败!");
            }
        }
        return mv;
    }

    //    根据条件修改登录表信息
    @RequestMapping("goUpdateLogin.emp")
    public ModelAndView goUpdateLoginEnd(long loginID) {
        ModelAndView mv = new ModelAndView("backEnd/updateLoginEnd");
        XzLogin xzLogin = loginService.selByLoginIDEnd(loginID);
        System.out.println("goUpdateLogin.emp" + xzLogin.getLoginId());
        mv.addObject("xzLogin", xzLogin);
        return mv;
    }

    //    根据条件修改登录表信息
    @RequestMapping("updateLogin.emp")
    public ModelAndView updateLoginEnd(@Validated({XzLogin.F2.class}) XzLogin xzLogin, BindingResult result) {
        ModelAndView mv = new ModelAndView("backEnd/updateLoginEnd");

        if (result.hasErrors()) {
            System.out.println(xzLogin);
        } else {
            mv.setViewName("redirect:selAllLogin.emp");
            XzLogin xzLogin1 = new XzLogin();
//        比较密码 若有改动则重新MD5加密
            xzLogin1 = loginService.selByLoginIDEnd(xzLogin.getLoginId());
            System.out.println(xzLogin.getLoginPassword());
            System.out.println(xzLogin1.getLoginPassword());
            if (!xzLogin.getLoginPassword().equals(xzLogin1.getLoginPassword())) {
                xzLogin.setLoginPassword(MD5.md5(xzLogin.getLoginPassword()));
            }

            if (xzLogin.getDeleteFalt() == 1) {
                xzLogin.setDeleteLoginDate(new Date());
            }
            int a = loginService.updateLoginEnd(xzLogin);
            if (a != 0) {
                System.out.println("修改成功!");
            } else {
                System.out.println("修改失败!");
            }
            xzLogin1 = loginService.selByLoginIDEnd(xzLogin.getLoginId());
            mv.addObject("xzLogin", xzLogin1);
        }
        return mv;
    }

    //    根据条件删除登录表信息
    @RequestMapping("deleteLogin.emp")
    public ModelAndView deleteLoginEnd(long loginID) {
        ModelAndView mv = new ModelAndView("redirect:selAllLogin.emp");
        XzLogin xzLogin = new XzLogin();
        xzLogin.setLoginId(loginID);
        xzLogin.setDeleteFalt(1);
        xzLogin.setDeleteLoginDate(new Date());
        int a = loginService.updateLoginEnd(xzLogin);
        if (a != 0) {
            System.out.println("删除成功!");
        } else {
            System.out.println("删除失败!");
        }
        return mv;
    }


    //    跳转到后台主页
    /*@RequestMapping("/goIndex.emp")
    public ModelAndView goBackEndIndex(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) {
        ModelAndView mv = new ModelAndView("backEnd/backEndIndex");
        return mv;
    }
*/
    //    管理员登录
    /*@RequestMapping("/goLogin.emp")
    public ModelAndView goLoginEnd() {
        ModelAndView mv = new ModelAndView("backEnd/loginAdminEnd");
        XzLogin xzLogin = new XzLogin();
        mv.addObject("xzLogin", xzLogin);
        return mv;
    }*/

    //后台管理员登录
    @RequestMapping("/LoginBack3.emp")
    public ModelAndView loginBack3(String username, String password) {
        ModelAndView mv = new ModelAndView("backEnd3/login_back");
        XzLogin xzLogin = new XzLogin();
        xzLogin.setLoginCount(username);
        xzLogin.setLoginPassword(MD5.md5(password));
        XzLogin admin = loginService.selLoginAdmin(xzLogin);
        System.out.println(admin);
        if (admin != null) {
            mv.addObject("adminLogin", admin);
            mv.setViewName("backEnd3/index_home");
        } else {
            mv.addObject("msg", "用户名或密码错误!");
        }
        return mv;
    }

    //  注销
    @RequestMapping("exitAdmin.emp")
    public ModelAndView exitAdmin(SessionStatus sessionStatus, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("backEnd3/login_back");
        sessionStatus.setComplete();//清空session
        return mv;
    }

    @RequestMapping("selAllLoginEmp.emp")
    public ModelAndView selAllLoginEmp(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer rows, XzLogin xzLogin) {
        ModelAndView mv = new ModelAndView("backEnd3/loginEmp");
        PageBean<XzLogin> pageBean = loginService.selAllLoginEnd(page, rows, xzLogin);
        List<XzLogin> loginList = pageBean.getList();
        mv.addObject("loginList", loginList);
        mv.addObject("page", pageBean.getPageNum());
        mv.addObject("pages", pageBean.getPages());
        mv.addObject("rows", pageBean.getPageSize());
        mv.addObject("total", pageBean.getTotal());
        mv.addObject("xzLogin", xzLogin);
        return mv;
    }

    //按LoginId查询
    @RequestMapping("selLoginByLoginId.emp")
    public ModelAndView selLoginByLoginId(Long LoginId, int a) {
        ModelAndView mv = new ModelAndView("backEnd3/revise_login");
        XzLogin xzLogin = loginService.selLoginId(LoginId);
        if (a == 2) {
            mv.setViewName("backEnd3/revise_loginUpdate");
        }
        mv.addObject("login", xzLogin);
        return mv;
    }

    //管理员后台修改
    @RequestMapping("updateAdminLog.emp")
    public ModelAndView updateAdminLog(XzLogin xzLogin) {
        ModelAndView mv = new ModelAndView("redirect:selAllLoginEmp.emp");
        Map map = new HashMap();
        xzLogin.setLoginPassword(MD5.md5(xzLogin.getLoginPassword()));
        int i = loginService.updateAdminLog(xzLogin);
        if (i == 1) {
            map.put("msg", "ok");
        } else {
            map.put("msg", "err");
        }
        mv.addObject("map", map);
        return mv;
    }

}